/**
 * 简化版微信小程序登录工具模块
 * 专为混合方案设计：先尝试获取微信用户信息，失败则手动输入
 */

import { wxLogin, checkLoginStatus, logout } from '../api/api.js'

class EnhancedAuthManager {
    constructor() {
        this.isLogging = false // 防止重复登录
        this.loginPromise = null // 登录Promise缓存
    }

    /**
     * 检查是否已登录
     */
    isLoggedIn() {
        const token = uni.getStorageSync('token')
        return token && token.trim() !== ''
    }

    /**
     * 获取用户信息
     */
    getUserInfo() {
        return uni.getStorageSync('userInfo') || null
    }

    /**
     * 保存登录信息
     */
    saveLoginInfo(token, userInfo) {
        uni.setStorageSync('token', token)
        uni.setStorageSync('userInfo', userInfo)
        console.log('💾 登录信息已保存:', { 
            token: token.substring(0, 20) + '...', 
            userInfo: {
                id: userInfo.id,
                nickname: userInfo.nickname,
                phone: userInfo.phone
            }
        })
    }

    /**
     * 清除登录信息
     */
    clearLoginInfo() {
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        console.log('🗑️ 登录信息已清除')
    }

    /**
     * 自动登录流程
     */
    async autoLogin() {
        if (this.isLogging) {
            return this.loginPromise
        }

        console.log('🔍 开始自动登录检查...')

        // 检查是否已登录
        if (this.isLoggedIn()) {
            try {
                console.log('🔐 检查现有token有效性...')
                const result = await checkLoginStatus()
                if (result.valid) {
                    console.log('✅ 用户已登录，token有效')
                    return {
                        success: true,
                        isLoggedIn: true,
                        userInfo: result.userInfo
                    }
                }
            } catch (error) {
                console.log('⚠️ Token验证失败，需要重新登录:', error)
                this.clearLoginInfo()
            }
        }

        console.log('📝 用户未登录，需要授权')
        return {
            success: true,
            isLoggedIn: false,
            needAuth: true
        }
    }

    /**
     * 微信登录API调用（混合方案专用）
     */
    async wxLogin(loginData) {
        try {
            console.log('🌐 调用微信登录API...')
            console.log('📋 登录数据:', {
                hasCode: !!loginData.code,
                hasEncryptedData: !!loginData.encryptedData,
                hasUserInfo: !!loginData.userInfo,
                nickName: loginData.userInfo?.nickName,
                timestamp: loginData.timestamp
            })
            
            // 调用API方法
            const result = await wxLogin(loginData);
            
            console.log('✅ 登录API调用成功:', result)
            
            // 根据后台返回格式处理数据
            console.log('🔍 解析后台返回数据:', result)
            
            if (result.token&&result.user) {
                // 处理嵌套的data.data结构
                const responseData = result
                return {
                    success: true,
                    token: responseData.token,
                    userInfo: {
                        id: responseData.user.id,
                        aid: responseData.user.aid,
                        openid: responseData.user.openid,
                        unionid: responseData.user.unionid,
                        phone: responseData.user.phone,
                        nickname: responseData.user.nickname,
                        avatar: responseData.user.avator,
                        isNewUser: false
                    }
                }
            } else if (result.code === 0) {
                // 处理单层data结构（备用）
                return {
                    success: true,
                    token: result.data.token,
                    userInfo: {
                        id: result.data.user.id,
                        aid: result.data.user.aid,
                        openid: result.data.user.openid,
                        unionid: result.data.user.unionid,
                        phone: result.data.user.phone,
                        nickname: result.data.user.nickname,
                        avatar: result.data.user.avator,
                        isNewUser: false
                    }
                }
            } else {
                const errorMsg = (result.data && result.data.msg) || result.msg || '登录失败'
                throw new Error(errorMsg)
            }
        } catch (error) {
            console.error('❌ 登录API调用失败:', error)
            throw error
        }
    }

    /**
     * 退出登录
     */
    async performLogout() {
        try {
            console.log('🚪 正在退出登录...')
            await logout()
            this.clearLoginInfo()
            
            uni.showToast({
                title: '已退出登录',
                icon: 'success'
            })

            console.log('✅ 退出登录成功')
            return { success: true }
        } catch (error) {
            console.error('❌ 退出登录失败:', error)
            return { success: false, error: error.message }
        }
    }

    /**
     * 更新用户信息
     */
    updateUserInfo(newUserInfo) {
        const currentUserInfo = this.getUserInfo()
        const updatedUserInfo = { ...currentUserInfo, ...newUserInfo }
        uni.setStorageSync('userInfo', updatedUserInfo)
        console.log('📝 用户信息已更新:', updatedUserInfo)
    }

    /**
     * 检查用户是否有特定权限
     */
    hasPermission(permission) {
        const userInfo = this.getUserInfo()
        const permissions = userInfo?.permissions || []
        return permissions.includes(permission)
    }
}

// 创建单例实例
const enhancedAuthManager = new EnhancedAuthManager()

export default enhancedAuthManager

// 导出常用方法
export const {
    isLoggedIn,
    getUserInfo,
    autoLogin,
    performLogout,
    updateUserInfo,
    hasPermission
} = enhancedAuthManager